<template>
  <div class="container">
    <!-- 侧边栏树结构保持不变 -->
    <div class="sidebar" style="width: 20%;">
      <el-tree :data="GCtreeData" :props="TreeProps" class="letree" default-expand-all :expand-on-click-node="false"
        @node-click="handleNodeClick" ref="treeRef" node-key="id">
      </el-tree>
    </div>

    <div class="main">
      <div class="header">
        <!-- 操作按钮保持不变 -->
        <el-button type="primary" @click="handleNew">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="danger" :loading="deleting" @click="batchDelete">批量删除</el-button>

        <!-- 日期选择器和搜索框保持不变 -->
        <div class="date-picker-container">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="起始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </div>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
        <el-button type="info" @click="query" style="background-color: orange;">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>

      <!-- 统一动态表格 -->
      <el-table :empty-text="emptyText" :data="currentTableData" border class="eltable"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- 动态列渲染 -->
        <template v-for="column in dynamicColumns" :key="column.prop">
          <el-table-column :prop="column.prop" :label="column.label" :width="column.width"
            v-if="!column.hidden"></el-table-column>
        </template>                
        <el-table-column label="创建人">admin</el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalItems"
            layout="total, prev, pager, next, jumper"
          ></el-pagination> -->
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <template v-for="item in dialogItems" :key="item.prop">
          <el-form-item :prop="item.prop" :label="item.label" :rules="formRules[item.prop]">
            <el-input v-if="item.type === 'input'" v-model="formData[item.prop]" :placeholder="`请输入${item.label}`"
              :readonly="item.readonly" />
            <el-input v-if="item.type === 'textarea'" v-model="formData[item.prop]" type="textarea" :rows="3" />
            <el-select v-if="item.type === 'select'" v-model="formData[item.prop]" :placeholder="`请选择${item.label}`">
              <el-option v-for="option in item.options" :key="option[item.optionValue]"
                :label="option[item.optionLabel]" :value="option[item.optionValue]" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, nextTick, computed, readonly } from "vue";
import { ElTree, ElMessage, ElSelect, ElOption, ElMessageBox } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";

export default {
  setup() {

    const emptyText = "暂无数据";
    const dateRange = ref(["", ""]); // 默认值为空数组
    const selectedRows = ref([]); // 新增：存储选中的行数据
    const selectedNodeId = ref(null);
    const selectedNodeTag = ref(0);
    const selectedParentNodeId = ref(null);
    const GCtreeData = ref([]);

    const searchTable = ref("");
    const date1 = ref("");
    const date2 = ref("");

    const currentTableType = ref("GC"); // 动态类型标识：GC/CJ/SCX/GW
    const currentTableData = ref([]);   // 动态数据

    const dialogVisible = ref(false);
    const dialogTitle = ref("");
    const editMode = ref(false);
    const formData = ref({});
    const formRef = ref(null);
    const dialogItems = ref([]);
    const factoryOptions = ref([]); // 工厂下拉选项
    const workshopOptions = ref([]); // 车间下拉选项
    const lineOptions = ref([]);    // 生产线下拉选项

    const TreeProps = {
      children: "children",
      label: "label",
    };
    const treeRef = ref(null);

    const generateAutoCode = (type) => {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const randomNumber = Math.floor(1000 + Math.random() * 9000);
      return `${type}${year}${month}${day}${randomNumber}`;
    };

    const getDynamicColumns = (type) => {
      const columnsMap = {
        GC: [
          { prop: "gc_create_time", label: "创建时间" },
          { prop: "gc_code", label: "工厂编号" },
          { prop: "gc_name", label: "工厂名称" },
          { prop: "gc_address", label: "工厂地址" },
          { prop: "gc_remark", label: "备注" },
        ],
        CJ: [
          { prop: "cj_create_time", label: "创建时间" },
          { prop: "cj_code", label: "车间编号" },
          { prop: "cj_name", label: "车间名称" },
          { prop: "gc_name", label: "所属工厂" },
          { prop: "cj_remark", label: "备注" },
          { prop: "gc_id", label: "所属工厂ID", hidden: true }
        ],
        SCX: [
          { prop: "scx_create_time", label: "创建时间" },
          { prop: "scx_code", label: "生产线编号" },
          { prop: "scx_name", label: "生产线名称" },
          { prop: "cj_name", label: "所属车间" },
          { prop: "gc_name", label: "所属工厂" },
          { prop: "scx_remark", label: "备注" },
          { prop: "cj_id", label: "所属车间ID", hidden: true },
        ],
        GW: [
          { prop: "gw_create_time", label: "创建时间" },
          { prop: "gw_code", label: "工位编号" },
          { prop: "gw_name", label: "工位名称" },
          { prop: "scx_name", label: "所属生产线" },
          { prop: "cj_name", label: "所属车间" },
          { prop: "gc_name", label: "所属工厂" },
          { prop: "gw_remark", label: "备注" },
          { prop: "scx_id", label: "所属生产线ID", hidden: true },
        ]
      };
      return columnsMap[type] || [];
    };

    // 表单验证规则
    const formRules = ref({
      gc_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      gc_address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
      cj_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      scx_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      gw_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      gc_id: [{ required: true, message: '请选择工厂', trigger: 'change' }],
      cj_id: [{ required: true, message: '请选择车间', trigger: 'change' }],
      scx_id: [{ required: true, message: '请选择生产线', trigger: 'change' }],
    });

    // 动态表单项配置
    const formConfigMap = {
      GC: [
        { prop: "gc_code", label: "工厂编号", type: "input", readonly: "ture" },
        { prop: "gc_name", label: "工厂名称", type: "input" },
        { prop: "gc_address", label: "工厂地址", type: "input" },
        { prop: "gc_remark", label: "备注", type: "textarea" }
      ],
      CJ: [
        { prop: "cj_code", label: "车间编号", type: "input", readonly: "ture" },
        { prop: "cj_name", label: "车间名称", type: "input" },
        {
          prop: "gc_id",
          label: "所属工厂",
          type: "select",
          options: factoryOptions,
          optionLabel: "gc_name",
          optionValue: "gc_id"
        },
        { prop: "cj_remark", label: "备注", type: "textarea" }
      ],
      SCX: [
        { prop: "scx_code", label: "生产线编号", type: "input", readonly: "ture" },
        { prop: "scx_name", label: "生产线名称", type: "input" },
        {
          prop: "cj_id",
          label: "所属车间",
          type: "select",
          options: workshopOptions,
          optionLabel: "cj_name",
          optionValue: "cj_id"
        },
        { prop: "scx_remark", label: "备注", type: "textarea" }
      ],
      GW: [
        { prop: "gw_code", label: "工位编号", type: "input", readonly: "ture" },
        { prop: "gw_name", label: "工位名称", type: "input" },
        {
          prop: "scx_id",
          label: "所属生产线",
          type: "select",
          options: lineOptions,
          optionLabel: "scx_name",
          optionValue: "scx_id"
        },
        { prop: "gw_remark", label: "备注", type: "textarea" }
      ]
    };

    // 获取选项数据
    const fetchOptions = async (type) => {
      try {
        switch (type) {
          case 'factory':
            const res = await axios.get("/api/GC/GetGC");
            factoryOptions.value = res.data;
            break;
          case 'workshop':
            const res2 = await axios.get(`/api/GC/GetCJ?gc_id=${selectedParentNodeId.value}`);
            workshopOptions.value = res2.data;
            break;
          case 'line':
            const res3 = await axios.get(`/api/GC/GetSCX?cj_id=${selectedParentNodeId.value}`);
            lineOptions.value = res3.data;
            break;
        }
      } catch (error) {
        console.error("获取选项失败:", error);
      }
    };

    // 打开对话框通用方法
    const openDialog = (type, rowData = null) => {
      editMode.value = !!rowData;
      dialogTitle.value = `${editMode.value ? '编辑' : '新增'}${getTypeName(type)}`;
      dialogItems.value = formConfigMap[type];
      formData.value = rowData ? { ...rowData } : {};

      // 根据类型加载选项数据
      switch (type) {
        case 'CJ': fetchOptions('factory'); break;
        case 'SCX': fetchOptions('workshop'); break;
        case 'GW': fetchOptions('line'); break;
      }

      dialogVisible.value = true;
    };

    const getTypeName = (type) => {
      const names = { GC: '工厂', CJ: '车间', SCX: '生产线', GW: '工位' };
      return names[type] || '';
    };

    // 具体类型对话框方法
    const dialogGC = (row) => openDialog('GC', row);
    const dialogCJ = (row) => openDialog('CJ', row);
    const dialogSCX = (row) => openDialog('SCX', row);
    const dialogGW = (row) => openDialog('GW', row);

   // 提交表单
   const submitForm = async () => {
      try {
        await formRef.value.validate();

        const apiMap = {
          GC: editMode.value ? '/api/GC/UpdateGC' : '/api/GC/AddGC',
          CJ: editMode.value ? '/api/GC/UpdateCJ' : '/api/GC/AddCJ',
          SCX: editMode.value ? '/api/GC/UpdateSCX' : '/api/GC/AddSCX',
          GW: editMode.value ? '/api/GC/UpdateGW' : '/api/GC/AddGW'
        };

        console.log(formData.value);

        const submitData = { ...formData.value };
        const remarkField = `${currentTableType.value.toLowerCase()}_remark`; // 根据类型动态获取字段名（如 gc_remark）
        if (!submitData[remarkField]) submitData[remarkField] = ""; // 空值处理

        const response = await axios[editMode.value ? 'put' : 'post'](
          apiMap[currentTableType.value],
          submitData // 使用处理后的数据
        );

        // 修改判断逻辑
        if (response.data && response.data.success) {
          ElMessage.success(editMode.value ? '修改成功' : '新增成功');
          dialogVisible.value = false;
          fetchTreeData();
          fetchTableData();
        } else {
          ElMessage.error('操作失败，请检查数据');
        }
      } catch (error) {
        ElMessage.error(`操作失败: ${error.response?.data?.message || error.message}`);
      }
    };

    // 编辑行
    const handleEdit = (row) => {
      switch (currentTableType.value) {
        case 'GC': dialogGC(row); break;
        case 'CJ': dialogCJ(row); break;
        case 'SCX': dialogSCX(row); break;
        case 'GW': dialogGW(row); break;
      }
    };

    // 重置表单
    const resetForm = () => {
      formRef.value?.resetFields();
      formData.value = {};
    };

    const dynamicColumns = computed(() => {
      console.log("当前表格类型:", currentTableType.value); // 打印表格类型
      return getDynamicColumns(currentTableType.value);
    });

    // 获取树状图数据
    const fetchTreeData = async () => {
      try {
        // 获取生产制造工厂数据
        const gcsResponse = await axios.get("/api/GC/GetGC");
        const gcs = gcsResponse.data.map((gc) => ({
          id: gc.gc_id,
          label: gc.gc_name,
          children: [],
          tag: 1
        }));

        // 获取车间数据
        for (const gc of gcs) {
          const cjsResponse = await axios.get(
            `/api/GC/GetCJ?gc_id=${gc.id}`
          );
          gc.children = cjsResponse.data.map((cj) => ({
            id: cj.cj_id,
            label: cj.cj_name,
            gc_id: cj.gc_id,
            children: [],
            tag: 2
          }));
        }

        // 获取生产线数据
        for (const gc of gcs) {
          for (const cj of gc.children) {
            const scxsResponse = await axios.get(
              `/api/GC/GetSCX?cj_id=${cj.id}`
            );
            cj.children = scxsResponse.data.map((scx) => ({
              id: scx.scx_id,
              label: scx.scx_name,
              cj_id: scx.cj_id,
              tag: 3
            }));
          }
        }

        // 构建“全部”节点
        const allNode = {
          id: "all",
          label: "全部",
          children: gcs,
          tag: 0
        };

        GCtreeData.value = [allNode];

        // // 默认选中“全部”节点
        // nextTick(() => {
        //   if (treeRef.value) {
        //     console.log("[Debug] 设置当前节点键值:", allNode.id); // 调试输出
        //     treeRef.value.setCurrentKey(allNode.id);
        //     handleNodeClick(allNode);
        //   }
        // });
      } catch (error) {
        console.error("Error fetching tree data:", error);
      }
    };

    const handleNodeClick = async (data) => {
      console.log("[Debug] 点击节点:", data);
      selectedNodeTag.value = data.tag;
      selectedNodeId.value = data.id;

      // 根据节点类型提取父节点 ID
      let parentId;
      switch (data.tag) {
        case 2: // 车间节点，父节点是工厂 ID (gc_id)
          parentId = data.gc_id;
          break;
        case 3: // 生产线节点，父节点是车间 ID (cj_id)
          parentId = data.cj_id;
          break;
        default:
          parentId = null;
      }
      selectedParentNodeId.value = parentId; // 存储父节点 ID

      console.log("[Debug] 当前 tag:", selectedNodeTag.value);
      console.log("[Debug] 当前 ID:", selectedNodeId.value);
      console.log("父节点id:", selectedParentNodeId.value);

      // 根据 tag 设置表格类型
      const tableTypeMap = { 0: "GC", 1: "CJ", 2: "SCX", 3: "GW" };
      currentTableType.value = tableTypeMap[data.tag] || "GC";

      await nextTick(); // 等待 DOM 更新
      fetchTableData();
    };

    const fetchTableData = async () => {
      try {
        let res;
        switch (currentTableType.value) {
          case "GC":
            res = await axios.get("/api/GC/GetGC");
            break;
          case "CJ":
            res = await axios.get(`/api/GC/GetCJ?gc_id=${selectedNodeId.value}`);
            break;
          case "SCX":
            res = await axios.get(`/api/GC/GetSCX?cj_id=${selectedNodeId.value}`);
            break;
          case "GW":
            res = await axios.get(`/api/GC/GetGW?scx_id=${selectedNodeId.value}`);
            break;
        }

        // 格式化日期字段
        const formattedData = res.data.map((item) => {
          return {
            ...item,
            gc_create_time: item.gc_create_time ? dayjs(item.gc_create_time).format("YYYY-MM-DD") : "", // 格式化工厂创建时间
            cj_create_time: item.cj_create_time ? dayjs(item.cj_create_time).format("YYYY-MM-DD") : "", // 格式化车间创建时间
            scx_create_time: item.scx_create_time ? dayjs(item.scx_create_time).format("YYYY-MM-DD") : "", // 格式化生产线创建时间
            gw_create_time: item.gw_create_time ? dayjs(item.gw_create_time).format("YYYY-MM-DD") : "", // 格式化工位创建时间
          };
        });

        currentTableData.value = formattedData; // 绑定格式化后的数据
        console.log("当前表格数据:", currentTableData.value); // 打印绑定数据
      } catch (error) {
        ElMessage.error("数据加载失败");
      }
    };

     const query = async () => {
  try {
    // 构建请求参数
    const params = {
      str: searchTable.value.trim() || undefined, // 搜索关键字（空字符串转为 undefined）
    };

    // 处理日期范围（date1 和 date2）
    if (dateRange.value && dateRange.value.length === 2) {
      params.date1 = dateRange.value[0];
      params.date2 = dateRange.value[1];
    }

    // 根据当前层级动态添加父级 ID 参数
    switch (currentTableType.value) {
      case "CJ":
        params.gc_id = selectedNodeId.value; // 车间需要工厂 ID
        break;
      case "SCX":
        params.cj_id = selectedNodeId.value; // 生产线需要车间 ID
        break;
      case "GW":
        params.scx_id = selectedNodeId.value; // 工位需要生产线 ID
        break;
    }

    // 清理 undefined 参数
    const cleanedParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined)
    );

    // 根据类型选择接口地址
    const endpoints = {
      GC: "/api/GC/GetGC",
      CJ: "/api/GC/GetCJ",
      SCX: "/api/GC/GetSCX", // 修正接口路径
      GW: "/api/GC/GetGW"      // 修正接口路径
    };

    // 发送请求
    const res = await axios.get(endpoints[currentTableType.value], {
      params: cleanedParams
    });

    // 格式化日期字段
    currentTableData.value = res.data.map(item => ({
      ...item,
      gc_create_time: item.gc_create_time ? dayjs(item.gc_create_time).format("YYYY-MM-DD") : "",
      cj_create_time: item.cj_create_time ? dayjs(item.cj_create_time).format("YYYY-MM-DD") : "",
      scx_create_time: item.scx_create_time ? dayjs(item.scx_create_time).format("YYYY-MM-DD") : "",
      gw_create_time: item.gw_create_time ? dayjs(item.gw_create_time).format("YYYY-MM-DD") : ""
    }));

  } catch (error) {
    ElMessage.error(`查询失败: ${error.response?.data?.message || error.message}`);
  }
};

    const reset = () => {
      dateRange.value = ["", ""]; // 清空日期选择器
      searchTable.value = ""; // 清空搜索框
      fetchTableData(); // 重新查询
    };

    const handleNew = () => {
      // 生成自动编号
      const code = generateAutoCode(currentTableType.value);

      // 根据节点类型打开对应弹窗
      switch (selectedNodeTag.value) {
        case 0: dialogGC(); break;
        case 1: dialogCJ(); break;
        case 2: dialogSCX(); break;
        case 3: dialogGW(); break;
      }

      // 根据类型初始化表单数据（合并原有数据，避免覆盖）
      const codeField = `${currentTableType.value.toLowerCase()}_code`;
      formData.value = {
        ...formData.value,  // 保留可能存在的其他字段
        [codeField]: code   // 动态设置编号字段
      };
    };

    const handleSelectionChange = (selection) => {
      selectedRows.value = selection;
    };

    const deleteRow = async (row) => {
      try {
        await ElMessageBox.confirm('确认删除该数据吗？', '提示', { type: 'warning' });
        const idKey = `${currentTableType.value.toLowerCase()}_id`;
        const idValue = row[idKey];

        // 新接口规范
        const apiMap = {
          GC: `/api/GC/DelGC?id=${idValue}`,
          CJ: `/api/GC/DelCJ?id=${idValue}`,
          SCX: `/api/GC/DelSCX?id=${idValue}`,
          GW: `/api/GC/DelGW?id=${idValue}`
        };

        const response = await axios.put(apiMap[currentTableType.value]);

        if (response.data?.success) {
          ElMessage.success('删除成功');
          fetchTreeData();
          fetchTableData();
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`删除失败: ${error.response?.data?.message || error.message}`);
        }
      }
    };

    const batchDelete = async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条数据');
        return;
      }

      try {
        await ElMessageBox.confirm('确认删除选中的数据吗？', '提示', { type: 'warning' });
        const idKey = `${currentTableType.value.toLowerCase()}_id`;
        const ids = selectedRows.value.map(row => row[idKey]);

        // 新接口规范
        const apiMap = {
          GC: '/api/GC/DelGCs',
          CJ: '/api/GC/DelCJs',
          SCX: '/api/GC/DelSCXs',
          GW: '/api/GC/DelGWs'
        };

        const response = await axios.put(
          apiMap[currentTableType.value],
          ids, // 直接发送数组
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );

        if (response.data?.success) {
          ElMessage.success(`成功删除${selectedRows.value.length}条数据`);
          selectedRows.value = [];
          fetchTreeData();
          fetchTableData();
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`批量删除失败: ${error.response?.data?.message || error.message}`);
        }
      }
    };


    // 初始化加载数据
    onMounted(() => {
      fetchTreeData();
      fetchTableData();
    });

    return {
      deleteRow,
      batchDelete,
      handleSelectionChange,
      selectedNodeTag,
      selectedNodeId,
      currentTableData,
      dynamicColumns,
      dateRange,
      treeRef,
      GCtreeData,
      TreeProps,
      handleNodeClick,
      handleNew,
      dialogGC,
      dialogCJ,
      dialogSCX,
      dialogGW,
      fetchTableData,
      emptyText,
      query,
      date1,
      date2,
      dialogVisible,
      dialogTitle,
      formData,
      formRef,
      dialogItems,
      submitForm,
      resetForm,
      handleEdit,
      factoryOptions,
      workshopOptions,
      lineOptions,
      formRules,
      reset,
      searchTable
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 87vh;
  font-size: 16PX;
}

.sidebar {
  height: 100%;
  width: 30vh;
}

.letree {
  height: 97%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.date-picker-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px, 0;
}

.eltable {
  width: 100%;
  height: 100%;
  min-height: 300px;
  /* 设置最小高度 */
  font-size: 12px;
  /* 调整字体大小 */
}
</style>